package cn.klaw.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.PropertySource;

/**
 * 将Spring中的配置设置到系统属性中
 * conf2system:
 *   csp.sentinel.log.dir: log/${spring.application.name}/sentinel
 *   rocketmq.log.level: "OFF"
 *   demo.enabled: false
 *
 *
 * @version V5.1.0
 *
 * @date 2024-12-17
 */
@Slf4j
public class Conf2SystemConfiguration implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {

    private static final String PREFIX = "conf2system.";

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        for (PropertySource<?> source : applicationContext.getEnvironment().getPropertySources()) {
            if(source instanceof EnumerablePropertySource){
                for (String propertyName : ((EnumerablePropertySource<?>) source).getPropertyNames()) {
                    if(propertyName.startsWith(PREFIX)){
                        Object value = environment.getProperty(propertyName);
                        if(value != null){
                            System.setProperty(propertyName.substring(PREFIX.length()), String.valueOf(value));
                            if(log.isDebugEnabled()){
                                log.debug("Setting system property [{}] to [{}]", propertyName.substring(PREFIX.length()), value);
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE+1000;
    }
}
